/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.myapp.struts;

import com.myapp.beans.Helper;
import com.myapp.entities.User;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.JOptionPane;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Vinh_Dragon
 */
public class LoginAction extends org.apache.struts.action.Action {
    
    /* forward name="success" path="" */
    private static final String SUCCESS = "loginSuccess";
    private static final String Student = "dosurvey";
    private static final String Error = "loginAgain";
    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        com.myapp.beans.LoginFormBean loginFormBean= (com.myapp.beans.LoginFormBean)form;
        String username, password, role;

        username = loginFormBean.getUsername();
        password = loginFormBean.getPassword();

        com.myapp.beans.Helper helper = new Helper();

        ArrayList<User> list = new ArrayList<User>();
        list = helper.getListUser(this.getServlet().getServletContext().getRealPath("/"));
        for (int i= 0; i < list.size(); i++) {
            
            if (username.equals(list.get(i).getUsername()) && password.equals(list.get(i).getPassword())) {
                HttpSession sess = request.getSession(true);
                sess.setAttribute("username", username);
                
                if (list.get(i).getRole().equals("student")) {
                    return mapping.findForward(Student);
                }else if(list.get(i).getRole().equals("admin")){
                    return mapping.findForward(SUCCESS);
                }else{
                    
                }
            }
        }
        JOptionPane.showMessageDialog(null, "User name or password is invalid, please try again...");
        
        return mapping.findForward(Error);
    }
}
